package com.authine.cloudpivot.engine.plugin.service.impl;

import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.SelectionValue;
import com.authine.cloudpivot.engine.model.ProjectTaskIssueModel;
import com.authine.cloudpivot.engine.model.TaskReportModel;
import com.authine.cloudpivot.engine.plugin.domain.SampleList;
import com.authine.cloudpivot.engine.plugin.service.TaskReportService;
import com.authine.cloudpivot.engine.repository.DJCustomerdemandListRepository;
import com.authine.cloudpivot.engine.repository.SampleListRepository;
import com.authine.cloudpivot.engine.repository.SubjectRepository;
import com.authine.cloudpivot.engine.repository.TaskReportRepository;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.misc.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: zyj
 * @time: 2021/6/17 17:46
 */
@Service
@Transactional
public class TaskReportServiceImpl implements TaskReportService {

    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private TaskReportRepository taskReportRepository;
    @Autowired
    private SubjectRepository subjectRepository;
    @Autowired
    private SampleListRepository sampleListRepository;
    @Autowired
    private DJCustomerdemandListRepository dJCustomerdemandListRepository;

    private BizObjectFacade bizObjectFacade;
    @Autowired
    public void setBizObjectFacade( BizObjectFacade bizObjectFacade) {
        this.bizObjectFacade = bizObjectFacade;
    }

    @Override
    public Boolean getXiaFaDataLejuan() {
        //qc下发信息
        List<Map<String, Object>> taskQCReport = taskReportRepository.getTaskQCReport();
        if(CollectionUtils.isEmpty(taskQCReport)){
            return null;
        }
        //构建qc下发统计map,用户名+项目名+任务名作为key
        Map<String, List<Map<String, Object>>> sumMap = new HashMap<>();
        for (Map<String, Object> map : taskQCReport) {
            String qc_name = MapUtils.getString(map, "QC_name");
            String project_name = MapUtils.getString(map, "project_name");
            String qc_task_name = MapUtils.getString(map, "QC_task_name");
            String key = qc_name + qc_task_name + project_name;
            if(sumMap.containsKey(key)){
                List<Map<String, Object>> maps = sumMap.get(key);
                maps.add(map);
                sumMap.put(key, maps);
            }else{
                List<Map<String, Object>> maps = new ArrayList<>();
                maps.add(map);
                sumMap.put(key, maps);
            }
        }
        //循环数据，计算各种值
        List<ProjectTaskIssueModel> returnList = new ArrayList<>();
        for (String s : sumMap.keySet()) {
            ProjectTaskIssueModel model = new ProjectTaskIssueModel();
            List<Map<String, Object>> maps = sumMap.get(s);
            Integer sum1 = 0;
            Integer sum2 = 0;
            Integer sum3 = 0;
            Integer sum4 = 0;
            Integer sum5 = 0;
            for (Map<String, Object> map : maps) {
                String state = MapUtils.getString(map, "state");
                Integer count = MapUtils.getInteger(map, "count");
                if("未审核".equals(state)){
                    sum1 += count;
                }else if("已审核".equals(state)){
                    sum2 += count;
                }else if("待跟进".equals(state)){
                    sum3 += count;
                }else if("无效问卷".equals(state)){
                    sum4 += count;
                }else if("未提交".equals(state)){
                    sum5 += count;
                }
            }
            Map<String, Object> map = maps.get(0);
            model.setProject_name(MapUtils.getString(map,"project_name"));
            model.setQC_task_name(MapUtils.getString(map,"QC_task_name"));
            model.setQC_name(MapUtils.getString(map, "QC_name"));
            model.setTask_sum(sum1+sum2+sum3+sum4);
            model.setEnd_sum(sum2+sum4);
            model.setNoend_sum(sum1+sum3);
            model.setStay_number(sum3);
            model.setInvalid_number(sum4);
            model.setNosub_sum(sum5);
            if((sum1+sum2+sum3+sum4)==0){
                model.setEnd_proportion("0.00");
            }else{
                model.setEnd_proportion(String.format("%.2f", (float) (sum2+sum4) / (float) (sum1+sum2+sum3+sum4) * 100) + "");
            }
            model.setDjxq(MapUtils.getString(map,"djxq"));
            returnList.add(model);
        }
        getSumDataLejuan(returnList);
        return true;
    }

    private void getSumDataLejuan(List<ProjectTaskIssueModel> returnList){
        Map<String, Map<String, Integer>> map = new HashMap<>();
        for (ProjectTaskIssueModel issueModel : returnList) {
            String id = issueModel.getDjxq();
            Map<String, Integer> dataMap = map.get(id);
            if(MapUtils.isEmpty(dataMap)){
                dataMap = new HashMap<>();
                dataMap.put("task_sum",0);
                dataMap.put("noend_sum",0);
                dataMap.put("end_sum",0);
                dataMap.put("stay_number",0);
                dataMap.put("invalid_number",0);
                map.put(id,dataMap);
            }
            if(MapUtils.isNotEmpty(dataMap)){
                Integer task_sum = issueModel.getTask_sum() + dataMap.get("task_sum");
                Integer noend_sum = issueModel.getNoend_sum() + dataMap.get("noend_sum");
                Integer end_sum = issueModel.getEnd_sum() + dataMap.get("end_sum");
                Integer stay_number = issueModel.getStay_number() + dataMap.get("stay_number");
                Integer invalid_number = issueModel.getInvalid_number() + dataMap.get("invalid_number");
                dataMap.put("task_sum",task_sum);
                dataMap.put("noend_sum",noend_sum);
                dataMap.put("end_sum",end_sum);
                dataMap.put("stay_number",stay_number);
                dataMap.put("invalid_number",invalid_number);
                dataMap.put("nosub_sum",issueModel.getNosub_sum());
                map.put(id,dataMap);
            }
        }
        for (String s : map.keySet()) {
            Map<String, Object> storeCount = taskReportRepository.getStoreCount(s);
            BigDecimal bs = (BigDecimal)storeCount.get("storeCount");
            int store_count = bs.intValue();
            Map<String, Integer> data = map.get(s);
            double d1;
            double d2;
            Integer ysh = data.get("end_sum");
            Integer dgj = data.get("stay_number");
            Integer zf = data.get("invalid_number");
            if(store_count==0){
                d1 = 0.00;
            }else{
                d1 = (float) (data.get("task_sum")-zf) / (float) (store_count) * 100;
            }
            if((data.get("task_sum"))==0){
                d2 = 0.00;
            }else{
                d2 = (float) (data.get("end_sum")) / (float) (data.get("task_sum")) * 100;
            }
            taskReportRepository.updateQCTask(data.get("task_sum"),data.get("end_sum"),data.get("stay_number"),data.get("invalid_number"),d1,d2,s,data.get("task_sum")-ysh-dgj,data.get("nosub_sum"));
        }
    }

    @Override
    public String getProjects() {
        List<Map<String, String>> projects = taskReportRepository.getProjects();
        TaskReportModel model = new TaskReportModel();
        model.setProjects(projects);
        return JSON.toJSONString(model);
    }

    @Override
    public Boolean moveSubject(String oldUserId, String newUserId, String subjectCode) {
        String XMKXX = "iden7_XMKXX";
        String XMBJ = "iden7_XMBJ";
        String XMZF = "iden7_XMZF";
        String XMLX = "iden7_XMLX";
        String XMQD = "iden7_XMQD";
        String ProjectTeam = "iden7_ProjectTeam";
        String XZZPXQ = "iden7_XZZPXQ";
        String XZDJXQ = "iden7_XZDJXQ";
        String XMZZ = "iden7_XMZZ";
        String XMKHGL = "iden7_XMKHGL";
        String projecttask = "iden7_projecttask";

        String WHMDXX = "iden7_WHMDXX";
        String ZPXQRS = "iden7_ZPXQRS";
        String PostJD = "iden7_PostJD";

        Map<String, String> idByCode = subjectRepository.getIdByCode(subjectCode);
        //项目可行性id
        Map<String, String> kxxId = subjectRepository.getKXXIdByCode(subjectCode);
        if(idByCode==null){
            return null;
        }
        String id = idByCode.get("id");
        String subjectPerson = "[{\"id\":\"" + newUserId + "\",\"type\":3}]";

        List<String> list = new ArrayList<>();
        String sql1 = "update " + XMKXX + " set owner = '" + newUserId + "',subjectPerson = '" + subjectPerson + "' where projectNo = '" + subjectCode + "'";
        String sql2 = "update " + XMBJ + " set owner = '" + newUserId + "' where subjectName = '" + kxxId + "'";
        String sql3 = "update " + XMZF + " set owner = '" + newUserId + "' where subjectName = '" + id + "'";
        String sql4 = "update " + XMLX + " set owner = '" + newUserId + "',subjectPerson = '" + subjectPerson + "' where projectNo = '" + subjectCode + "'";
        String sql5 = "update " + XMQD + " set owner = '" + newUserId + "',subjectPerson = '" + subjectPerson + "' where projectNo = '" + subjectCode + "'";
        String sql6 = "update " + ProjectTeam + " set owner = '" + newUserId + "' where subjectName = '" + id + "'";
        String sql7 = "update " + XZZPXQ + " set owner = '" + newUserId + "' where subjectName = '" + id + "'";
        String sql8 = "update " + XZDJXQ + " set owner = '" + newUserId + "' where subjectName = '" + id + "'";
        String sql9 = "update " + XMZZ + " set owner = '" + newUserId + "' where subjectName = '" + id + "'";
        String sql10 = "update " + XMKHGL + " set owner = '" + newUserId + "',manager = '" + subjectPerson  + "' where project = '" + id + "'";
        String sql11 = "update " + projecttask + " set owner = '" + newUserId + "',projectmanager = '" + subjectPerson + "' where projectNo = '" + subjectCode + "'";
        String sql12 = "update " + WHMDXX + " set owner = '" + newUserId + "',eManager = '" + subjectPerson + "' where projectNo = '" + subjectCode + "'";
        String sql13 = "update " + ZPXQRS + " set owner = '" + newUserId + "'" + "where projectNo = '" + subjectCode + "'";
        String sql14 = "update " + PostJD + " set owner = '" + newUserId + "'" + "where subject = '" + id + "'";
        list.add(sql1);
        list.add(sql2);
        list.add(sql3);
        list.add(sql4);
        list.add(sql5);
        list.add(sql6);
        list.add(sql7);
        list.add(sql8);
        list.add(sql9);
        list.add(sql10);
        list.add(sql11);
        list.add(sql12);
        list.add(sql13);
        list.add(sql14);
        for (String sql : list) {
            Query query = entityManager.createNativeQuery(sql);
            query.executeUpdate();
        }
        return null;
    }

    @Override
    public Boolean createZiJianQCReport() {
        //qc自建下发信息
        List<Map<String, Object>> taskZiJianQCReport = taskReportRepository.getTaskZiJianQCReport();
        if(CollectionUtils.isEmpty(taskZiJianQCReport)){
            return null;
        }
        //构建自建qc下发统计map
        Map<String, List<Map<String, Object>>> sumMap = new HashMap<>();
        for (Map<String, Object> map : taskZiJianQCReport) {
            String qc_name = MapUtils.getString(map, "QC_name");
            String relevance_task_name = MapUtils.getString(map, "relevance_task_name");
            String key = qc_name + relevance_task_name;
            if(sumMap.containsKey(key)){
                List<Map<String, Object>> maps = sumMap.get(key);
                maps.add(map);
                sumMap.put(key, maps);
            }else{
                List<Map<String, Object>> maps = new ArrayList<>();
                maps.add(map);
                sumMap.put(key, maps);
            }
        }
        //循环数据，计算各种值
        List<ProjectTaskIssueModel> list = new ArrayList<>();
        for (String s : sumMap.keySet()) {
            List<Map<String, Object>> maps = sumMap.get(s);
            ProjectTaskIssueModel model = new ProjectTaskIssueModel();
            Integer sum1 = 0;
            Integer sum2 = 0;
            Integer sum3 = 0;
            Integer sum4 = 0;
            for (Map<String, Object> map : maps) {
                String state = MapUtils.getString(map, "questionnaireStatus");
                Integer count = MapUtils.getInteger(map, "count");
                if("未审核".equals(state)){
                    sum1 += count;
                }else if("已审核".equals(state)){
                    sum2 += count;
                }else if("待跟进".equals(state)){
                    sum3 += count;
                }else if("无效样本".equals(state)){
                    sum4 += count;
                }
            }
            Map<String, Object> map = maps.get(0);
            model.setRelevanceQC_task(MapUtils.getString(map,"relevance_task_name"));
            model.setQC_task_name(MapUtils.getString(map,"task_name"));
            model.setQC_name(MapUtils.getString(map, "QC_name"));
            model.setTask_sum(sum1+sum2+sum3+sum4);
            model.setEnd_sum(sum2+sum4);
            model.setNoend_sum(sum1+sum3);
            model.setStay_number(sum3);
            model.setInvalid_number(sum4);
            if((sum1+sum2+sum3+sum4)==0){
                model.setEnd_proportion("0.00");
            }else{
                model.setEnd_proportion(String.format("%.2f", (float) (sum2+sum4) / (float) (sum1+sum2+sum3+sum4) * 100) + "");
            }
            list.add(model);
        }
        //删除统计数据
        taskReportRepository.deleteZiJianTask();
        BizObjectModel bizObjectModel;
        Map<String, Object> data;
        for(ProjectTaskIssueModel issueModel : list) {
            bizObjectModel = new BizObjectModel();
            bizObjectModel.setSchemaCode("self_task_send");
            bizObjectModel.setFormCode("self_task_send");
            bizObjectModel.setSequenceStatus("COMPLETED");
            data = bizObjectModel.getData();
            data.put("relevance_task_name", issueModel.getRelevanceQC_task());
            data.put("task_sum", issueModel.getTask_sum());
            data.put("end_sum", issueModel.getEnd_sum());
            data.put("noend_sum", issueModel.getNoend_sum());
            data.put("end_proportion", issueModel.getEnd_proportion());
            data.put("stay_number", issueModel.getStay_number());
            data.put("invalid_number", issueModel.getInvalid_number());
            data.put("task_name", issueModel.getQC_task_name());
            String userId = issueModel.getQC_name();
            if(StringUtils.isNotBlank(userId)){
                userId = userId.substring(8, 40);
                Map<String, String> name = taskReportRepository.getName(userId);
                data.put("QcUserName", name.get("name"));
            }else{
                data.put("QcUserName", "");
                Map<String, String> id = taskReportRepository.getAdminId();
                userId = id.get("id");
            }
            String s = bizObjectFacade.saveBizObject(userId, bizObjectModel, false);
            if(StringUtils.isNotBlank(issueModel.getQC_name())){
                taskReportRepository.updateZiJianTaskSendQcName(issueModel.getQC_name(),s);
            }
        }
        createSumZiJianQCReport(list);
        return true;
    }

    private void createSumZiJianQCReport(List<ProjectTaskIssueModel> list){
        Map<String, Map<String, Integer>> map = new HashMap<>();
        for (ProjectTaskIssueModel issueModel : list) {
            String id = issueModel.getRelevanceQC_task();
            Map<String, Integer> dataMap = map.get(id);
            if(MapUtils.isEmpty(dataMap)){
                dataMap = new HashMap<>();
                dataMap.put("task_sum",0);
                dataMap.put("noend_sum",0);
                dataMap.put("end_sum",0);
                dataMap.put("stay_number",0);
                dataMap.put("invalid_number",0);
                map.put(id,dataMap);
            }
            if(MapUtils.isNotEmpty(dataMap)){
                Integer task_sum = issueModel.getTask_sum() + dataMap.get("task_sum");
                Integer noend_sum = issueModel.getNoend_sum() + dataMap.get("noend_sum");
                Integer end_sum = issueModel.getEnd_sum() + dataMap.get("end_sum");
                Integer stay_number = issueModel.getStay_number() + dataMap.get("stay_number");
                Integer invalid_number = issueModel.getInvalid_number() + dataMap.get("invalid_number");
                dataMap.put("task_sum",task_sum);
                dataMap.put("noend_sum",noend_sum);
                dataMap.put("end_sum",end_sum);
                dataMap.put("stay_number",stay_number);
                dataMap.put("invalid_number",invalid_number);
                map.put(id,dataMap);
            }
        }
        for (String s : map.keySet()) {
            Map<String, Integer> data = map.get(s);
            double d1;
            Integer ysh = data.get("end_sum");
            Integer dgj = data.get("stay_number");
            if((data.get("task_sum"))==0){
                d1 = 0.00;
            }else{
                d1 = (float) (data.get("end_sum")) / (float) (data.get("task_sum")) * 100;
            }
            taskReportRepository.updateZiJianQCTask(data.get("task_sum"),data.get("end_sum"),data.get("stay_number"),data.get("invalid_number"),d1,s,data.get("task_sum")-ysh-dgj);
        }
    }

    @Override
    public Boolean updateSampleList() {
        Map<String, String> updateSelfBuiltTask = taskReportRepository.getUpdateSelfBuiltTask();
        String id = updateSelfBuiltTask.get("id");
        String selfTask = updateSelfBuiltTask.get("selfTask");
        //更改的样本
        List<Map<String, Object>> sampleListChange = taskReportRepository.getSampleListChange(id);
        //删除原本的样本
        taskReportRepository.deleteSampleList(selfTask);
        //保存样本
        List<SampleList> list = new ArrayList<>();
        for (Map<String, Object> map : sampleListChange) {
            SampleList sampleList = new SampleList();
            sampleList.setObject(MapUtils.getString(map,"object"));
            sampleList.setSortKey((BigDecimal)map.get("sortKey"));
            sampleList.setParentId(selfTask);
            list.add(sampleList);
        }
        sampleListRepository.saveAll(list);
        return true;
    }

    @Override
    public Boolean updateStoreState(String recruitmentId, String state) {
        taskReportRepository.updateStoreState(recruitmentId, state);
        return true;
    }

    @Override
    public Boolean delOffLineReport(Date currentTime, String recuitmentId) {
        taskReportRepository.delOffLineReport(currentTime, recuitmentId);
        return true;
    }

    @Override
    public Boolean delOnLineReport(Date currentTime, String recuitmentId) {
        taskReportRepository.delOnLineReport(currentTime, recuitmentId);
        return true;
    }


    @Override
    public void updateDemandFor(String recruitmentType, String idCode, BigDecimal demandFor, String storeContacts, String contactsPhone, String comment) {
        if(!"不确定人数".equals(recruitmentType)) {
            if (demandFor != null && demandFor.intValue() == 0) {
                taskReportRepository.updateDemandFor(idCode, demandFor, storeContacts, contactsPhone, comment, "已取消");
            } else {
                taskReportRepository.updateDemandFor(idCode, demandFor, storeContacts, contactsPhone, comment, "进行中");
            }
        }else{
            taskReportRepository.updateDemandFor(idCode, demandFor, storeContacts, contactsPhone, comment, "进行中");
        }
    }

    @Override
    public void updateRecruitmentState(String id, String state) {
        taskReportRepository.updateRecruitmentState(id, state);
    }

    @Override
    public Boolean hasRole(String userId, String roleId) {
        Integer count = taskReportRepository.hasRole(userId, roleId);
        if(count == null){
            return false;
        }
        return count > 0;
    }

    @Override
    public void updateOnlineReportInfo(double onlineRecruitmentNum, double projectProvideNum, String comment, String id) {
        taskReportRepository.updateOnlineReportInfo(onlineRecruitmentNum, projectProvideNum, comment, id);
    }

    @Override
    public void updateOffLineReport(double plannedNum, double finishedNum, double recommendNum, String councilor, String comment, String resubmisPerson, String id) {
        taskReportRepository.updateOffLineReport(plannedNum, finishedNum, recommendNum,councilor, comment, resubmisPerson, id);
    }

    @Override
    public void updateOffLineReportInfo(double mgFinishedNum, double clientProvideNum, double projectProvideNum, String id) {
        taskReportRepository.updateOffLineReportInfo(mgFinishedNum, clientProvideNum, projectProvideNum, id);
    }

    @Override
    public List<String> getRecruitmentIds(List<String> idList, String recruitWay) {
        if("线上".equals(recruitWay)) {
            return  taskReportRepository.getOnLineRecruitmentIds(idList);
        }else{
            return taskReportRepository.getOffLineRecruitmentIds(idList);
        }
    }

    @Override
    public void updateReportMgrInfo(String recuitmentId, String recruitWay, boolean isNeedExecute) {
        if("线上".equals(recruitWay)) {
            Map<String, BigDecimal> map = taskReportRepository.getOnLineReportMgrInfo(recuitmentId);
            taskReportRepository.updateOnLineReportMgrInfo(map.get("communicateNum"), map.get("inviteNum"), map.get("toFaceNum"), map.get("offerNum"), map.get("entryNum"), map.get("demandFor"), recuitmentId);
            taskReportRepository.updateOnLineRecruitment(map.get("communicateNum"), map.get("inviteNum"), map.get("toFaceNum"), map.get("offerNum"),  map.get("entryNum"), map.get("demandFor"), recuitmentId);

        }else {
            String recruitmentType = taskReportRepository.getRecruitmentType(recuitmentId);
            List<Map<String, Object>> listMap = taskReportRepository.getOffLineReport(recuitmentId);
            if ("不确定人数".equals(recruitmentType)) {
                double plannedNum = 0.0;
                double recommendNum = 0.0;
                double recommendRate = 0.0;
                for (Map<String, Object> map : listMap) {
                    //推荐数=中台招聘完成数+客户提供数+项目组提供数
                    if (map.get("MGFinishedNum") != null || map.get("clientProvideNum") != null || map.get("projectProvideNum") != null) {
                        recommendNum += (map.get("MGFinishedNum") != null ? Double.parseDouble(map.get("MGFinishedNum").toString()) : 0.0)
                                + (map.get("clientProvideNum") != null ? Double.parseDouble(map.get("clientProvideNum").toString()) : 0.0)
                                + (map.get("projectProvideNum") != null ? Double.parseDouble(map.get("projectProvideNum").toString()) : 0.0);
                    } else {
                        recommendNum += (map.get("recommendNum") != null ? Double.parseDouble(map.get("recommendNum").toString()) : 0.0);
                    }
                    //计划数
                    plannedNum += map.get("plannedNum") != null ? Double.parseDouble(map.get("plannedNum").toString()) : 0.0;
                }
                if (plannedNum == 0) {
                    recommendRate = 0;
                } else {
                    recommendRate = recommendNum / plannedNum * 100;
                }
                taskReportRepository.updateOffLineReportMgrInfo1(recommendNum, plannedNum, recommendRate, recuitmentId);
                taskReportRepository.updateOffLineRecruitment1(recommendNum, plannedNum, recommendRate, recuitmentId);


                // 完成数反写到 需求明细里
                if(isNeedExecute){
                    //填报的推荐数据 反写到 需求明细里
                    taskReportRepository.updateOffLineRecruitmentDetail11(recuitmentId);
                }else {
                    //复核的 中台完成数据+客户提供数+项目提供数  反写到需求明细
                    taskReportRepository.updateOffLineRecruitmentDetail22(recuitmentId);
                }

            } else {
                double demandFor = Double.parseDouble(taskReportRepository.getDemandFor(recuitmentId).toString());
                double finishedNum = 0.0;
                double finishingRate = 0.0;

                for (Map<String, Object> map : listMap) {
                    if (map.get("MGFinishedNum") != null || map.get("clientProvideNum") != null || map.get("projectProvideNum") != null) {
                        finishedNum += (map.get("MGFinishedNum") != null ? Double.parseDouble(map.get("MGFinishedNum").toString()) : 0.0)
                                + (map.get("clientProvideNum") != null ? Double.parseDouble(map.get("clientProvideNum").toString()) : 0.0)
                                + (map.get("projectProvideNum") != null ? Double.parseDouble(map.get("projectProvideNum").toString()) : 0.0);
                    } else {
                        finishedNum += (map.get("finishedNum") != null ? Double.parseDouble(map.get("finishedNum").toString()) : 0.0);
                    }
                }

                if (demandFor == 0) {
                    finishingRate = 0;
                } else {
                    finishingRate = finishedNum / demandFor * 100;
                }
                taskReportRepository.updateOffLineReportMgrInfo2(finishedNum, demandFor, finishingRate, recuitmentId);
                taskReportRepository.updateOffLineRecruitment2(finishedNum, finishingRate, finishingRate, recuitmentId);

                // 完成数反写到 需求明细里
                if(isNeedExecute){
                    //填报的 完成数 反写到需求明细
                    taskReportRepository.updateOffLineRecruitmentDetail21(recuitmentId);
                }else {
                    //复核的 中台完成数据+客户提供数+项目提供数  反写到需求明细
                    taskReportRepository.updateOffLineRecruitmentDetail22(recuitmentId);
                }
            }

        }
    }

    @Override
    public ArrayList<Object[]> getReportCreateTimeList(String recuitmentId, String recruitWay) {
        if("线上".equals(recruitWay)) {
            return taskReportRepository.getOnLineReportCreateTimeList(recuitmentId);
        }else{
            return taskReportRepository.getOffLineReportCreateTimeList(recuitmentId);
        }
    }

    @Override
    public void delWeeklyReport(List<String> delIds, String recruitWay) {
        if("线上".equals(recruitWay)) {
            taskReportRepository.delOnLineWeeklyReport(delIds);
        }else{
            taskReportRepository.delOffLineWeeklyReport(delIds);
        }
    }

    @Override
    public void updateWeeklyReportInfo(String recruitmentId, Date needFinishTime, String recruitWay) {
        if("线上".equals(recruitWay)) {
            taskReportRepository.updateOnLineWeeklyReportInfo(recruitmentId, needFinishTime);
        }else{
            taskReportRepository.updateOffLineWeeklyReportInfo(recruitmentId, needFinishTime);
        }
    }

    @Override
    public void updateWeeklyReportMgrInfo(String recruitmentId, Date needFinishTime, String recruitWay, String recruitmentType) {
        if("线上".equals(recruitWay)) {
            taskReportRepository.updateOnLineWeeklyReportMgrInfo(recruitmentId, needFinishTime);
        }else{
            if(!"不确定人数".equals(recruitmentType)) {
                taskReportRepository.updateOffLineWeeklyReportMgrInfo1(recruitmentId, needFinishTime);
            }else{
                taskReportRepository.updateOffLineWeeklyReportMgrInfo2(recruitmentId, needFinishTime);
            }
        }
    }

    @Override
    public void autoReviewReportMgrInfo() {
        //自动复核线上周报
        List<Map<String, Object>> onLineReportMap = taskReportRepository.getOnLineReportMgrInfo();
        onLineReportMap.forEach(
                map->{
                    taskReportRepository.updateOnLineReportMgrInfo((BigDecimal)map.get("communicateNum"), (BigDecimal)map.get("inviteNum"), (BigDecimal)map.get("toFaceNum"), (BigDecimal)map.get("offerNum"), (BigDecimal) map.get("entryNum"),(BigDecimal) map.get("demandFor"), map.get("recuitmentId").toString());
                }
        );
    }

    @Override
    public void delReportInfoByICode(String recruitWay, List<String> idCodes, Date nextMonday) {
        if("线上".equals(recruitWay)) {
            taskReportRepository.delOnLineReportByICode(idCodes,nextMonday);
        }else{
            taskReportRepository.delOffLineReportByICode(idCodes,nextMonday);
        }
    }

    @Override
    public void updateRCSArea(String id, String schemaCode) {
        if("demandDetails".equals(schemaCode)){
            //更新招聘需求提报子表rcs区域
            taskReportRepository.updateZPXQTBRCSArea(id);
        }else if("demandDetailList".equals(schemaCode)){
            //更新招聘需求b变更子表rcs区域
            taskReportRepository.updateZPXQBGRCSArea(id);
        } else if("executeDetails".equals(schemaCode)){
            //更新执行需求提报子表rcs区域
            taskReportRepository.updateZXXQTBRCSArea(id);
        }else if("executeDetailList".equals(schemaCode)){
            //更新执行需求变更子表rcs区域
            taskReportRepository.updateZXXQBGRCSArea(id);
        }
    }

    @Override
    public void updateExecuteDetail(String executeDetailId, BigDecimal newStoreNum, BigDecimal newPlanGearsNum, BigDecimal newPlanRoundNum) {
        taskReportRepository.updateExecuteDetail(executeDetailId,newStoreNum,newPlanGearsNum,newPlanRoundNum);

    }

    @Override
    public void updateExecuteReportInfo(String executeDetailId, BigDecimal newStoreNum, BigDecimal newPlanGearsNum, BigDecimal newPlanRoundNum) {
        taskReportRepository.updateExecuteReportInfo(executeDetailId,newStoreNum,newPlanGearsNum,newPlanRoundNum);
    }

    @Override
    public void updateExecuteMgrInfo(String executeId, Date activityStartTime, Date activityEndTime) {
        taskReportRepository.updateExecuteMgrInfo(executeId, activityStartTime, activityEndTime);
    }


    @Override
    public void updateExecuteReportTime(String executeId, Date oldWeekTime, Date newWeekTime) {
        taskReportRepository.updateExecuteReportTime(executeId,oldWeekTime,newWeekTime);
    }

    @Override
    public void delExecuteReport(List<String> executeIds) {
        taskReportRepository.delExecuteWeeklyReport(executeIds);
        taskReportRepository.delExecuteExecuteDemand(executeIds);
    }

    @Override
    public void updateExecuteReportEndTime(String executeDemandId, Date activityEndTime) {
        taskReportRepository.updateExecuteReportEndTime(executeDemandId, activityEndTime);
    }

    @Override
    public void createExecuteDetail(Map<String, Object> data) {
        taskReportRepository.createExecuteDetail(data.get("province"),data.get("city"),data.get("year"),data.get("cycle"),
                data.get("planRoundNum"),data.get("storeNum"),data.get("executeId"),data.get("executeDemandId"),data.get("modifier"),
                data.get("modifiedTime"),data.get("month"),data.get("planGearsNum"),data.get("area"),data.get("state"), data.get("dateRange"));
    }

    @Override
    public List<String> getExecuteDemandIds(List<String> idList) {
        return taskReportRepository.getExecuteDemandIds(idList);
    }


    @Override
    public void updateDetailState(String demandId, String year, String month, String cycle, String state) {
        taskReportRepository.updateDetailState(demandId,year,month,cycle,state);
    }

    @Override
    public void updateExecuteCreateReportTime(String demandId, String year, String month, String cycle, Date reportCreateTime) {
        taskReportRepository.updateExecuteCreateReportTime(demandId,year,month,cycle,reportCreateTime);
    }

    @Override
    public void updateExecuteDemandEndTime(String demandId, Date activityEndTime) {
        taskReportRepository.updateExecuteDemandEndTime(demandId,activityEndTime);
    }

    @Override
    public void updateExecuteReportByOp(double actualGearsNum, double actualRoundNum, String councilor, String remark, String resubmisPerson, String id, double reasonNum,String arePersons) {
        taskReportRepository.updateExecuteReportByOp(actualGearsNum,actualRoundNum,councilor,remark, resubmisPerson,id,reasonNum,arePersons);
    }

    @Override
    public void updateExecuteReportByPM(double mgGearsNum, double mgRoundNum, double projectProvideNum, double clientProvideNum, String id) {
        taskReportRepository.updateExecuteReportByPM(mgGearsNum,mgRoundNum,projectProvideNum,clientProvideNum,id);
    }

    @Override
    public void updateExecuteReportMgr(Set<String> demandIdSet,boolean isNeedExecute) {
        List<Map<String,Object>> executeReportList = Collections.EMPTY_LIST;
        //如果是执行填报 取明细里的实际值,不取中台复核的值
        if (isNeedExecute){
            executeReportList  = taskReportRepository.getExecuteReportInfo(new ArrayList<>(demandIdSet));
        }else{
            executeReportList  = taskReportRepository.getExecuteReviewReportInfo(new ArrayList<>(demandIdSet));
        }


        Map<String,List<Map<String,Object>>> executeReportMap = new HashMap<>();
        executeReportList.stream().forEach(item->{
            String executeDemandId = (String) item.get("executeDemandId");
            if(executeReportMap.containsKey(executeDemandId)){
                List<Map<String, Object>> maps = executeReportMap.get(executeDemandId);
                maps.add(item);
            }else{
                List<Map<String,Object>> maps =  new ArrayList<>();
                maps.add(item);
                executeReportMap.put(executeDemandId,maps);
            }
        });

        List<Map<String,Object>> executeMgrInfoList = taskReportRepository.getExecuteMgrInfo(new ArrayList<>(demandIdSet));
        Map<String,List<Map<String,Object>>> executeMgrInfoMap = new HashMap<>();
        executeMgrInfoList.stream().forEach(item->{
            String executeDemandId = (String) item.get("copyDemand");
            if(executeMgrInfoMap.containsKey(executeDemandId)){
                List<Map<String, Object>> maps = executeMgrInfoMap.get(executeDemandId);
                maps.add(item);
            }else{
                List<Map<String,Object>> maps =  new ArrayList<>();
                maps.add(item);
                executeMgrInfoMap.put(executeDemandId,maps);
            }
        });
        ArrayList<HashMap<String,Object>> insertMapList = new ArrayList<>();
        ArrayList<HashMap<String,Object>> updateMapList = new ArrayList<>();
        for(String demandId :demandIdSet){
            String parentId = null;
            List<Map<String, Object>> reportMapList = executeReportMap.get(demandId);
            List<Map<String, Object>> mgrInfoMapList = executeMgrInfoMap.get(demandId);
            Map<String, HashMap<String,Object>> maps = new HashMap<>();
            for(Map<String,Object> mgrInfoMap : mgrInfoMapList){
                HashMap<String, Object> mgrInfoHashMap = new HashMap<>(mgrInfoMap);
                String mgrValue =  MapUtils.getString(mgrInfoHashMap,"year","")+MapUtils.getString(mgrInfoHashMap,"month","")+MapUtils.getString(mgrInfoHashMap,"cycle","");
                maps.put(mgrValue,mgrInfoHashMap);
                parentId =   MapUtils.getString(mgrInfoHashMap,"parentId","");
            }
            for(Map<String, Object> reportMap : reportMapList){
                HashMap<String, Object> reportHashMap = new HashMap<>(reportMap);
                String reportValue =  MapUtils.getString(reportHashMap,"year","")+MapUtils.getString(reportHashMap,"month","")+MapUtils.getString(reportHashMap,"cycle","");
                if(maps.containsKey(reportValue)){
                    HashMap<String, Object> mgrInfoMap = maps.get(reportValue);
                    reportHashMap.put("id",mgrInfoMap.get("id"));
                    updateMapList.add(reportHashMap);
                }else{
                    reportHashMap.put("modifier",reportHashMap.get("creater"));
                    reportHashMap.put("modifierTime",new Date());
                    reportHashMap.put("parentId",parentId);
                    insertMapList.add(reportHashMap);
                }
            }
            if (isNeedExecute){ //填报
                taskReportRepository.updateTotalRate(demandId);
                taskReportRepository.updateDemandTotalRate(demandId);
            }else{// 复核
                taskReportRepository.updateTotalRateReview(demandId);
                taskReportRepository.updateDemandTotalRateReview(demandId);
            }
        }
        for(Map<String,Object> map: insertMapList){
            taskReportRepository.insertExecutePool(map.get("year"),map.get("month"),map.get("cycle"),map.get("storeNum"),map.get("planGearsNum"),map.get("actualGearsNum"),
                    map.get("planRoundNum"),map.get("actualRoundNum"),map.get("lGearsRate"),map.get("RoundRate"),map.get("modifier"),map.get("modifiedTime"),
                    map.get("parentId"),UUID.randomUUID().toString().replace("-", ""),map.get("reasonNum"));

            taskReportRepository.sortExecutePool();

        }
        for(Map<String,Object> map: updateMapList){
            taskReportRepository.updateExecutePool(map.get("storeNum"),map.get("planGearsNum"),map.get("actualGearsNum"),
                    map.get("planRoundNum"),map.get("actualRoundNum"),map.get("lGearsRate"),map.get("RoundRate"),
                    map.get("id"),map.get("reasonNum"));

            taskReportRepository.sortExecutePool();

        }
    }

    @Override
    public void updateReportCreateTime(String executeDemandId, List<String> cycleList, List<String> weeklyReportDayList) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(int i=0; i<weeklyReportDayList.size(); i++){
            String dateStr = weeklyReportDayList.get(i);
            String[] dateSplits = dateStr.split("-");
            String year = dateSplits[0];
            String month = dateSplits[1];
            String cycle = cycleList.get(i);
            Date reportCreateTime = null;
            try {
                reportCreateTime = sdf.parse(dateStr + " 23:59:59");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            taskReportRepository.updateReportCreateTime(executeDemandId,year,month,cycle,reportCreateTime);
        }
        taskReportRepository.updateExecuteRcsArea(executeDemandId);

    }

    @Override
    public void updateDemandDetailStatus() {
        //更新招聘需求明细状态
        List<String> idCodes = new ArrayList<>();
        List<String> onLineIdCodes  = taskReportRepository.getFinishedOnLineDetails();
        idCodes.addAll(onLineIdCodes);
        List<String> offLineIdCodes = taskReportRepository.getFinishedOffLineDetails();
        idCodes.addAll(offLineIdCodes);
        if(CollectionUtils.isNotEmpty(idCodes)) {
            taskReportRepository.updateRecruitmentDetailStatus(idCodes, "已完成");
        }

        List<String> idCodeList = new ArrayList<>();
        List<String> onLineIdCodeList  = taskReportRepository.getUnFinishedOnLineDetails();
        idCodeList.addAll(onLineIdCodeList);
        List<String> offLineIdCodeList = taskReportRepository.getUnFinishedOffLineDetails();
        idCodeList.addAll(offLineIdCodeList);
        if(CollectionUtils.isNotEmpty(idCodeList)) {
            taskReportRepository.updateRecruitmentDetailStatus(idCodeList, "进行中");
        }

        //更新执行需求明细状态
        WeekFields weekFields = WeekFields.ISO;
        List<String> years = new ArrayList<>();
        List<String> months = new ArrayList<>();
        List<String> cycles = new ArrayList<>();
        LocalDate today = LocalDate.now();
        LocalDate  lastMonday= today.minusDays(7).with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate lastSunday = today.minusDays(7).with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
        String[] lastMondays = lastSunday.toString().split("-");
        String[] lastSundays = lastSunday.toString().split("-");

        if(lastMonday.get(weekFields.of(DayOfWeek.MONDAY, 1).weekOfMonth()) == lastSunday.get(weekFields.of(DayOfWeek.MONDAY, 1).weekOfMonth())){
            years.add(lastMondays[0]);
            months.add(lastMondays[1]);
            cycles.add("W"+lastMonday.get(weekFields.of(DayOfWeek.MONDAY, 1).weekOfMonth()));
        }else{
            years.add(lastMondays[0]);
            months.add(lastMondays[1]);
            cycles.add("W"+lastMonday.get(weekFields.of(DayOfWeek.MONDAY, 1).weekOfMonth()));
            years.add(lastSundays[0]);
            months.add(lastSundays[1]);
            cycles.add("W"+lastSunday.get(weekFields.of(DayOfWeek.MONDAY, 1).weekOfMonth()));
        }

        for(int i=0; i< years.size();i++){
            taskReportRepository.updateExecuteDetailStateByCycle(years.get(i),months.get(i),cycles.get(i),"已结束");
        }
    }

    @Override
    public void delStoreByExecuteId(String executeId) {
        taskReportRepository.delStoreByExecuteId(executeId);
    }

    @Override
    public void updateRCSAreaByExecuteId(String executeId) {
        taskReportRepository.updateRCSAreaByExecuteId(executeId);
    }

    @Override
    public void updateAttrStatusByExecuteId(String executeId) {
        taskReportRepository.updateAttrStatusByExecuteId(executeId);
    }

    @Override
    public void updatePM(String originalPMId, String originalPMDeptId, String PMId, String PMDeptId, String projectName, String subjectName) {
        List<String> list = new ArrayList<>();

        String createrString = "[{\"id\":\""+PMId+"\",\"type\":"+3+"}]";

        String createrDeptString = "[{\"id\":\""+PMDeptId+"\",\"type\":"+2+"}]";


        // 任务工单 iden7_projecttask
        String sql1 = "update iden7_projecttask set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId +  "',projectmanager = '"+ createrString +"' where projectNames = '" + projectName + "'";

        // 组建项目组 ProjectTeam
        String sql2 = "update iden7_ProjectTeam set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "',subjectPerson = '"+ createrString +"' where subjectName = '" + projectName + "'";

        // 项目总监创建
        // 项目经理创建
        // 预通告 XMKXX
        String sql3 = "update iden7_XMKXX set xmfzr = '" + createrString + "' where id = '" + subjectName+"'" ;
        String sql4 = "update iden7_XMKXX set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where id = '" + subjectName + "' and creater = '" + originalPMId +"'";

        //预通告关闭 ytggb
        String sql5 = "update iden7_ytggb set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "',ssbm = '"+ createrDeptString + "',subjectPerson = '"+ createrString +"' where ytg = '" + subjectName + "'";

        //合同补交 bjht

        String sql6 = "update iden7_bjht set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "',ssbm = '"+ createrDeptString + "',subjectPerson = '"+ createrString +"' where xmmc = '" + projectName + "'";

        //项目延期 xmyqsq
        String sql7 = "update iden7_xmyqsq set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "',ssbm = '"+ createrDeptString + "',subjectPerson = '"+ createrString +"' where xmnane = '" + projectName + "'";

        //项目报价 XMBJ
        String sql8 = "update iden7_XMBJ set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId  + "',subjectPerson = '"+ createrString + "' where subjectName = '" + subjectName + "'";

        //岗位JD PostJD
        //String sql9 = "update iden7_PostJD set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId  +"' where subject = '" + projectName + "'";

        //门店信息 WHMDXX subjectName
        //String sql10 = "update iden7_WHMDXX set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId  +"' where subjectName = '" + projectName + "'";

        // 店检需求提报  DJXQ
        String sql9 = "update iden7_DJXQ set subjectPerson = '" + createrString + "' where subjectName = '" + projectName + "'";
        String sql10 = "update iden7_DJXQ set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where subjectName = '" + projectName + "' and creater = '" + originalPMId +"'";

        // 店检需求变更 DJXQBG
        String sql11 = "update iden7_DJXQBG set subjectPerson = '" + createrString + "' where subjectName = '" + projectName + "'";
        String sql12 = "update iden7_DJXQBG set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where subjectName = '" + projectName + "' and creater = '" + originalPMId +"'";

        //店检需求关闭 DJXQGB
        String sql13 = "update iden7_DJXQGB set subjectPerson = '" + createrString + "' where subjectName = '" + projectName + "'";
        String sql14 = "update iden7_DJXQGB set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where subjectName = '" + projectName + "' and creater = '" + originalPMId +"'";

        //店检需求结案 DJXQJA
        String sql15 = "update iden7_DJXQJA set subjectPerson = '" + createrString + "' where subjectName = '" + projectName + "'";
        String sql16 = "update iden7_DJXQJA set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where subjectName = '" + projectName + "' and creater = '" + originalPMId +"'";

        //店检问卷明细 ProjectTaskIssue
        String sql17 = "update iden7_ProjectTaskIssue set subjectPerson = '" + createrString + "' where subjectName = '" + projectName + "'";
        String sql18 = "update iden7_ProjectTaskIssue set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where subjectName = '" + projectName + "' and creater = '" + originalPMId +"'";

        //项目立项  XMQD
        String sql19 = "update iden7_XMQD set subjectPerson = '" + createrString + "' where id = '" + projectName + "'";
        String sql20 = "update iden7_XMQD set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where id = '" + projectName + "' and creater = '" + originalPMId +"'";

        // 招聘需求 recruitmentDemand
        String sql21 = "update iden7_recruitmentDemand set subjectPerson = '" + createrString + "' where projectName = '" + projectName + "'";
        String sql22 = "update iden7_recruitmentDemand set demandReceiver = '" + createrString + "' where projectName = '" + projectName  + "' and  demandReceiver like '%" + originalPMId +"%'";
        String sql23 = "update iden7_recruitmentDemand set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where projectName = '" + projectName + "' and creater = '" + originalPMId +"'";

        //招聘需求变更 recruitmentDemandUpdate
        String sql24 = "update iden7_recruitmentDemandUpdate set subjectPerson = '" + createrString + "' where projectName = '" + projectName + "'";;
        String sql25 = "update iden7_recruitmentDemandUpdate set demandReceiver = '" + createrString + "' where projectName = '" + projectName  + "' and  demandReceiver like '%" + originalPMId +"%'";
        String sql26 = "update iden7_recruitmentDemandUpdate set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where projectName = '" + projectName + "' and creater = '" + originalPMId +"'";

        //招聘需求关闭 ZPXQGB
        String sql27 = "update iden7_ZPXQGB set subjectPerson = '" + createrString + "' where projectName = '" + projectName + "'";
        String sql28 = "update iden7_ZPXQGB set demandReceiver = '" + createrString + "' where projectName = '" + projectName  + "' and  demandReceiver like '%" + originalPMId +"%'";
        String sql29 = "update iden7_ZPXQGB set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where projectName = '" + projectName + "' and creater = '" + originalPMId +"'";

        // 执行需求提报 ZXXQTB
        String sql30 = "update iden7_ZXXQTB set subjectPerson = '" + createrString + "' where projectName = '" + projectName + "'";;
        String sql31 = "update iden7_ZXXQTB set demandReceiver = '" + createrString +  "' where projectName = '" + projectName  + "' and  demandReceiver like '%" + originalPMId +"%'";
        String sql32 = "update iden7_ZXXQTB set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where projectName = '" + projectName + "' and creater = '" + originalPMId +"'";

        // 执行需求变更 ZXXQBG
        String sql33 = "update iden7_ZXXQBG set subjectPerson = '" + createrString + "' where projectName = '" + projectName + "'";;
        String sql34 = "update iden7_ZXXQBG set demandReceiver = '" + createrString + "' where projectName = '" + projectName  + "' and  demandReceiver like '%" + originalPMId +"%'";
        String sql35 = "update iden7_ZXXQBG set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where projectName = '" + projectName + "' and creater = '" + originalPMId +"'";

        // 执行需求关闭 ZXXQGB
        String sql36 = "update iden7_ZXXQGB set subjectPerson = '" + createrString + "' where projectName = '" + projectName + "'";;
        String sql37 = "update iden7_ZXXQGB set demandReceiver = '" + createrString + "' where projectName = '" + projectName  + "' and  demandReceiver like '%" + originalPMId +"%'";
        String sql38 = "update iden7_ZXXQGB set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where projectName = '" + projectName + "' and creater = '" + originalPMId +"'";

       // 线上招聘周报提交  XSZPZBTJ
        String sql39 = "update iden7_XSZPZBTJ set subjectPerson = '" + createrString + "' where projectName = '" + projectName + "' and isPigeonholed = '未归档'";
        String sql40 = "update iden7_XSZPZBTJ set frontOperator = '" + createrString + "',depart = '"+ createrDeptString + "' where projectName = '" + projectName  + "' and isPigeonholed = '未归档' and  frontOperator like '%" + originalPMId +"%'";
        String sql41 = "update iden7_XSZPZBTJ set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where projectName = '" + projectName + "' and creater = '" + originalPMId +"'";

        // 线下招聘周报提交 XXZPZBTJ
        String sql42 = "update iden7_XXZPZBTJ set subjectPerson = '" + createrString + "' where projectName = '" + projectName + "' and isPigeonholed = '未归档'";
        String sql43 = "update iden7_XXZPZBTJ set frontOperator = '" + createrString + "',depart = '"+ createrDeptString + "' where projectName = '" + projectName  + "' and isPigeonholed = '未归档' and  frontOperator like '%" + originalPMId +"%'";
        String sql44 = "update iden7_XXZPZBTJ set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where projectName = '" + projectName + "' and creater = '" + originalPMId +"'";

        // 执行周报明细 ZXZBMX
        String sql45 = "update iden7_ZXZBMX set subjectPerson = '" + createrString + "' where projectName = '" + projectName + "' and isPigeonholed = '未归档'";
        String sql46 = "update iden7_ZXZBMX set frontOperator = '" + createrString + "',depart = '"+ createrDeptString + "' where projectName = '" + projectName  + "' and isPigeonholed = '未归档' and  frontOperator like '%" + originalPMId +"%'";
        String sql47 = "update iden7_ZXZBMX set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where projectName = '" + projectName + "' and creater = '" + originalPMId +"'";

        // 线上招聘周报复核 ZPXQZBGL
        String sql48 = "update iden7_ZPXQZBGL set subjectPerson = '" + createrString + "' where subject = '" + projectName + "'";
        String sql49 = "update iden7_ZPXQZBGL set frontOperator = '" + createrString + "',depart = '"+ createrDeptString + "' where subject = '" + projectName  + "' and  frontOperator like '%" + originalPMId +"%'";
        String sql50 = "update iden7_ZPXQZBGL set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where subject = '" + projectName + "' and creater = '" + originalPMId +"'";

        // 线下招聘周报提交与复核 XXZPXQZBGL
        String sql51 = "update iden7_XXZPXQZBGL set subjectPerson = '" + createrString + "' where subject = '" + projectName + "'";
        String sql52 = "update iden7_XXZPXQZBGL set frontOperator = '" + createrString + "',depart = '"+ createrDeptString + "' where subject = '" + projectName  + "' and  frontOperator like '%" + originalPMId +"%'";
        String sql53 = "update iden7_XXZPXQZBGL set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where subject = '" + projectName + "' and creater = '" + originalPMId +"'";

        // 执行周报提交与复核 ZXZBGL
        String sql54 = "update iden7_ZXZBGL set subjectPerson = '" + createrString + "' where projectName = '" + projectName + "'";
        String sql55 = "update iden7_ZXZBGL set frontOperator = '" + createrString + "',depart = '"+ createrDeptString + "' where projectName = '" + projectName  + "' and  frontOperator like '%" + originalPMId +"%'";
        String sql56 = "update iden7_ZXZBGL set owner = '" + PMId + "',ownerDeptId = '" + PMDeptId  +  "',creater = '" + PMId +  "',createdDeptId = '" + PMDeptId + "' where projectName = '" + projectName + "' and creater = '" + originalPMId +"'";

        list.addAll(Arrays.asList(sql1,sql2,sql3,sql4,sql5,sql6,sql7,sql8,sql9,
                    sql10,sql11,sql12,sql13,sql14,sql15,sql16,sql17,sql18,sql19,
                    sql20,sql21,sql22,sql23,sql24,sql25,sql26,sql27,sql28,sql29,
                    sql30,sql31,sql32,sql33,sql34,sql35,sql36,sql37,sql38,sql39,
                    sql40,sql41,sql42,sql43,sql44,sql45,sql46,sql47,sql48,sql49,
                    sql50,sql51,sql52,sql53,sql54,sql55,sql56));

        for (String sql : list) {
            Query query = entityManager.createNativeQuery(sql);
            query.executeUpdate();
        }

    }

    @Override
    public void updateEM(Map<String, Object> data) {

        //"projectName","subjectPerson","executeDemand","executePM",
        //        "recruitmentDemand","recruitmentPM","DJDemand","DJPM"

        List<String> list = new ArrayList<>();
        String executeDemands  = (HashMap<String,Object>)data.get("executeDemand") != null ? ((HashMap<String,Object>)data.get("executeDemand")).get("id").toString() : null;
        String recruitmentDemands  = (HashMap<String,Object>)data.get("recruitmentDemand") != null ? ((HashMap<String,Object>)data.get("recruitmentDemand")).get("id").toString() : null;
        String DJDemands  = (HashMap<String,Object>)data.get("DJDemand") != null ? ((HashMap<String,Object>)data.get("DJDemand")).get("id").toString() : null;

        if(StringUtils.isNotBlank(executeDemands)){
            String executePM = ((ArrayList<SelectionValue>) data.get("executePM")).get(0).getId();
            String operatorName = ((ArrayList<SelectionValue>) data.get("executePM")).get(0).getId();
            String operatorString = "[{\"id\":\""+executePM+"\",\"type\":"+3+"}]";
            Arrays.stream(executeDemands.split(";")).forEach(
                    item->{
                        list.add("update iden7_ZXXQTB set operator = '" + operatorString + "' where id = '" + item + "'");
                        list.add("update iden7_ZXXQBG set operator = '" + operatorString + "' where copyDemand = '" + item + "'");
                        list.add("update iden7_ZXXQGB set operator = '" + operatorString + "' where copyDemand = '" + item + "'");
                        list.add("update iden7_ZXZBMX set operator = '" + operatorString + "' where executeDemandId = '" + item + "' and state = '未提交'");
                        list.add("update iden7_ZXZBGL set operator = '" + operatorString +"',operatorStr = '" + operatorName + "' where copyDemand = '" + item + "'");
                    }
            );

        }

        if(StringUtils.isNotBlank(recruitmentDemands)){
            String recruitmentPM = ((ArrayList<SelectionValue>) data.get("recruitmentPM")).get(0).getId();
            String operatorString = "[{\"id\":\""+recruitmentPM+"\",\"type\":"+3+"}]";
            Arrays.stream(recruitmentDemands.split(";")).forEach(
                    item->{
                        list.add("update iden7_recruitmentDemand set operator = '" + operatorString + "' where id = '" + item + "'");
                        list.add("update iden7_recruitmentDemandUpdate set operator = '" + operatorString + "' where copyDemand = '" + item + "'");
                        list.add("update iden7_ZPXQGB set operator = '" + operatorString + "' where recruitmentDemand = '" + item + "'");
                        list.add("update iden7_XSZPZBTJ set operator = '" + operatorString + "' where recuitmentId = '" + item + "' and state = '未提交'");
                        list.add("update iden7_XXZPZBTJ set operator = '" + operatorString + "' where recuitmentId = '" + item + "' and state = '未提交'");
                        list.add("update iden7_ZPXQZBGL set operator = '" + operatorString +"' where recruitmentDemand = '" + item + "'");
                        list.add("update iden7_XXZPXQZBGL set operator = '" + operatorString +"' where recruitmentDemand = '" + item + "'");
                    }
            );
        }

        if(StringUtils.isNotBlank(DJDemands)){
            String DJPM = ((ArrayList<SelectionValue>) data.get("DJPM")).get(0).getId();
            String operatorString = "[{\"id\":\""+DJPM+"\",\"type\":"+3+"}]";
            Arrays.stream(DJDemands.split(";")).forEach(
                    item->{
                        list.add("update iden7_DJXQ set executor = '" + operatorString + "' where id = '" + item + "'");
                        list.add("update iden7_DJXQBG set executor = '" + operatorString + "' where djxq = '" + item + "'");
                        list.add("update iden7_DJXQGB set executor = '" + operatorString + "' where djxq = '" + item + "'");
                        list.add("update iden7_DJXQJA set executor = '" + operatorString + "' where djxq = '" + item + "'");
                    }
            );
        }

        for (String sql : list) {
            Query query = entityManager.createNativeQuery(sql);
            query.executeUpdate();
        }
    }

    @Override
    public List<Map<String, Object>> getCalculateNum(HashMap<String, Set<String>> demandIdMap, String recruitWay) {
        List<Map<String, Object>> result = new ArrayList<>();
        if("线上".equals(recruitWay)) {
            for (String item : demandIdMap.keySet()) {
                Map tempMap = new HashMap<>();
                Set<String> set = demandIdMap.get(item);
                Map map = taskReportRepository.getOnLineCalculateNum(item, new ArrayList<>(set));
                if(map.get("existNum") == null){
                    tempMap.put("existNum",0.0);

                }else{
                    tempMap.put("existNum", Double.parseDouble(map.get("existNum").toString()));
                }
                tempMap.put("demandFor", Double.parseDouble(map.get("demandFor").toString()));
                tempMap.put("demandId",map.get("demandId"));
                result.add(tempMap);
            }
            return result;
        }else{
            for (String item : demandIdMap.keySet()) {
                Map tempMap = new HashMap<>();
                Set<String> set = demandIdMap.get(item);
                Map map = taskReportRepository.getOffLineCalculateNum(item, new ArrayList<>(set));

                if(map.get("existNum") == null){
                    tempMap.put("existNum",0.0);
                }else{
                    tempMap.put("existNum", Double.parseDouble(map.get("existNum").toString()));
                }
                tempMap.put("demandFor", Double.parseDouble(map.get("demandFor").toString()));
                tempMap.put("demandId",map.get("demandId"));
                result.add(tempMap);
            }
            return result;
        }
    }

    public static Date getLastSunDay(){
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        //获取前月的最后一天
        Calendar cale = Calendar.getInstance();
        //设置时间成本周第一天(周日)
        cale.set(Calendar.DAY_OF_WEEK,1);
        String lastDay = format.format(cale.getTime());
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        Date endTime = null;
        try {
            endTime = timeFormat.parse(lastDay + " 23:59:59");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return endTime;
    }

    public static Date getLastMonthLastDay(){
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        //获取前月的最后一天
        Calendar cale = Calendar.getInstance();
        cale.set(Calendar.DAY_OF_MONTH, 0);//设置为1号,当前日期既为本月第一天
        String lastDay = format.format(cale.getTime());
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        Date endTime = null;
        try {
            endTime = timeFormat.parse(lastDay + " 23:59:59");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return endTime;
    }

    public static Date getLastMonthFirstDay(){
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Calendar cal_1 = Calendar.getInstance();//获取当前日期
        cal_1.add(Calendar.MONTH, -1);
        cal_1.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        String firstDay = format.format(cal_1.getTime());
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        Date startTime = null;
        try {
            startTime = timeFormat.parse(firstDay + " 00:00:00");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return  startTime;
    }

    private Date getLastMonday(){
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Calendar cal_1 = Calendar.getInstance();//获取当前日期
        cal_1.set(Calendar.DAY_OF_WEEK,1);
        //上周一时间
        cal_1.add(Calendar.DATE, -6);
        String firstDay = format.format(cal_1.getTime());
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        Date startTime = null;
        try {
            startTime = timeFormat.parse(firstDay + " 00:00:00");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return  startTime;
    }

    @Override
    public void autoCloseDemand() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date date = calendar.getTime();
        //自动关闭招聘需求
        List<String>ids = taskReportRepository.getOverTimeRecruitmentDemand(date);
        ids.forEach(
                item->{
                    taskReportRepository.updateRecruitmentState(item,"已结束");
                    taskReportRepository.updateStoreState(item, "已取消");
                }
        );
        //自动关闭执行需求
        ids = taskReportRepository.getOverTimeExecuteDemand(date);
        ids.forEach(
                item->{
                    taskReportRepository.updateExecuteDemandState(item,"已结束");
                    taskReportRepository.updateExecuteDetailState(item,"已结束");
                }
        );
    }
    @Override
    public void autoCommitReport() {
        //自动关闭招聘需求
        //将线下招聘周报上上个星期的周报状态为未提交的周报设置成已提交
        //上周一
        Date startTime = getLastMonday();
        //上周日
        Date endTime = getLastSunDay();
        taskReportRepository.updateOfflineReportState(startTime, endTime, "已提交");
        //将执行周报上上个星期的周报状态为未提交的周报设置成已提交
        taskReportRepository.updateExecuteReportState(endTime, endTime, "已提交");
    }

    @Override
    public void autoReviewReport(String type) {
        Date startTime = getLastMonthFirstDay();
        Date endTime = getLastMonthLastDay();
        if("zx".equals(type)){
            taskReportRepository.autoReviewExecuteReport(startTime,endTime);
        }else if("zp".equals(type)){
            taskReportRepository.autoReviewOnlineReport(startTime,endTime);
            taskReportRepository.autoReviewOffLineReport(startTime,endTime);
        }


    }

    @Override
    public void autoArchiveReport(String type) {
        Date startTime = getLastMonthFirstDay();
        Date endTime = getLastMonthLastDay();
        if("zx".equals(type)){
            taskReportRepository.autoArchiveOnlineReport(startTime,endTime);
            taskReportRepository.autoArchiveOffLineReport(startTime,endTime);
        }else if("zp".equals(type)){
            taskReportRepository.autoArchiveExecuteReport(startTime,endTime);
        }
    }

    @Override
    public Map<String, String> getUncommittedReportTips() {
        Map<String, List<String>>  recruitMapList = new HashMap<>();
        Map<String, List<String>>  executeMapList = new HashMap<>();
        Map<String, String>  resultMap = new HashMap<>();
        //上周一
        Date startTime = getLastMonday();
        //上周日
        Date endTime = getLastSunDay();

        List<Map<String, Object>> offLineReportMap =  taskReportRepository.getUncommittedOffLineReport(startTime,endTime);

        List<Map<String, Object>> executeReportMap =  taskReportRepository.getUncommittedExecuteReport(startTime,endTime);

        if(offLineReportMap !=  null ){
            for(Map item : offLineReportMap){
                String projectName = item.get("projectNames").toString();
                String postJDStr = item.get("postJDStr").toString();
                String userId = item.get("operator").toString().split("\"")[3];
                if(recruitMapList.containsKey(userId)){
                    recruitMapList.get(userId).add("【"+projectName+"-"+postJDStr+"】");
                }else{
                    List<String> list =   new ArrayList<>();
                    list.add("【"+projectName+"-"+postJDStr+"】");
                    recruitMapList.put(userId,list);
                }
            }
        }else if( executeReportMap != null){
            for(Map item : executeReportMap) {
                String projectName = item.get("projectNames").toString();
                String activityName = item.get("activityName").toString();
                String userId = item.get("operator").toString().split("\"")[3];
                if (executeMapList.containsKey(userId)) {
                    executeMapList.get(userId).add("【"+projectName + "-" + activityName+"】");
                } else {
                    List<String> list = new ArrayList<>();
                    list.add("【"+projectName + "-" + activityName+"】");
                    executeMapList.put(userId, list);
                }
            }
        }
       // 暂时还未提交周报，请尽快提交
        for(String key: recruitMapList.keySet()){
            String value = "线下招聘需求：";
            List<String> values = recruitMapList.get(key);
            for(String item : values) {
                value  += item + ",";
            }
            value = value.substring(0,value.length()-1);
            resultMap.put(key,value);
        }

        for(String key: executeMapList.keySet()){
            String value = "执行需求：";
            List<String> values = executeMapList.get(key);
            for(String item : values) {
                value  += item + ",";
            }
            value = value.substring(0,value.length()-1);
            if(resultMap.containsKey(key)){
                resultMap.put(key,resultMap.get(key) + " " + value);
            }else{
                resultMap.put(key,value);
            }

        }
        return resultMap;
    }

    @Override
    public Map<String, String> getUnReviewedReportTips(String type) {
        Map<String, String>  resultMap = new HashMap<>();
        Date startTime = getLastMonthFirstDay();
        Date endTime = getLastMonthLastDay();
        if("zx".equals(type)){
            Map<String, List<String>>  executeMapList = new HashMap<>();
            List<Map<String, Object>> executeReportMap = taskReportRepository.getUnReviewedExecuteReport(startTime,endTime);
            if(executeReportMap != null){
                for(Map item : executeReportMap) {
                    String projectName = item.get("projectNames").toString();
                    String activityName = item.get("activityName").toString();

                    String personss = MapUtils.getString(item, "persons");
                    String subjectPersons = MapUtils.getString(item, "subjectPerson");
                    String frontOperators = MapUtils.getString(item, "frontOperator");
                    Set<String> set = new HashSet<>();
                    if(StringUtils.isNotBlank(personss)){
                        List<Map<String, String>> list = JSON.parseObject(personss, List.class);
                        for (Map<String, String> map : list) {
                            set.add(map.get("id"));
                        }
                    }
                    if(StringUtils.isNotBlank(subjectPersons)){
                        List<Map<String, String>> list = JSON.parseObject(subjectPersons, List.class);
                        for (Map<String, String> map : list) {
                            set.add(map.get("id"));
                        }
                    }
                    if(StringUtils.isNotBlank(frontOperators)){
                        List<Map<String, String>> list = JSON.parseObject(frontOperators, List.class);
                        for (Map<String, String> map : list) {
                            set.add(map.get("id"));
                        }
                    }
                    for (String userId : set) {
                        if (executeMapList.containsKey(userId)) {
                            executeMapList.get(userId).add("【"+projectName + "-" + activityName+"】");
                        } else {
                            List<String> list = new ArrayList<>();
                            list.add("【"+projectName + "-" + activityName+"】");
                            executeMapList.put(userId, list);
                        }
                    }
                }
                for(String key: executeMapList.keySet()){
                    String value = "执行需求：";
                    List<String> values = executeMapList.get(key);
                    for(String item : values) {
                        value  += item + ",";
                    }
                    value = value.substring(0,value.length()-1);
                    if(resultMap.containsKey(key)){
                        resultMap.put(key,resultMap.get(key) + " " + value);
                    }else{
                        resultMap.put(key,value);
                    }
                }
            }
        }else if("zp".equals(type)){
            Map<String, List<String>>  offlineMapList = new HashMap<>();
            Map<String, List<String>>  onlineMapList = new HashMap<>();
            List<Map<String, Object>> onLineReportMap = taskReportRepository.getUnReviewedOnlineReport(startTime,endTime);
            List<Map<String, Object>> offLineReportMap = taskReportRepository.getUnReviewedOffLineReport(startTime,endTime);
            if(offLineReportMap !=  null ){
                for(Map item : offLineReportMap){
                    String projectName = item.get("projectNames").toString();
                    String postJDStr = item.get("postJDStr").toString();

                    String personss = MapUtils.getString(item, "persons");
                    String subjectPersons = MapUtils.getString(item, "subjectPerson");
                    String frontOperators = MapUtils.getString(item, "frontOperator");
                    Set<String> set = new HashSet<>();
                    if(StringUtils.isNotBlank(personss)){
                        List<Map<String, String>> list = JSON.parseObject(personss, List.class);
                        for (Map<String, String> map : list) {
                            set.add(map.get("id"));
                        }
                    }
                    if(StringUtils.isNotBlank(subjectPersons)){
                        List<Map<String, String>> list = JSON.parseObject(subjectPersons, List.class);
                        for (Map<String, String> map : list) {
                            set.add(map.get("id"));
                        }
                    }
                    if(StringUtils.isNotBlank(frontOperators)){
                        List<Map<String, String>> list = JSON.parseObject(frontOperators, List.class);
                        for (Map<String, String> map : list) {
                            set.add(map.get("id"));
                        }
                    }
                    for (String userId : set) {
                        if(offlineMapList.containsKey(userId)){
                            offlineMapList.get(userId).add("【"+projectName+"-"+postJDStr+"】");
                        }else{
                            List<String> list =   new ArrayList<>();
                            list.add("【"+projectName+"-"+postJDStr+"】");
                            offlineMapList.put(userId,list);
                        }
                    }
                }
            }else if( onLineReportMap != null){
                for(Map item : onLineReportMap){
                    String projectName = item.get("projectNames").toString();
                    String postJDStr = item.get("postJDStr").toString();
                    String personss = MapUtils.getString(item, "persons");
                    String subjectPersons = MapUtils.getString(item, "subjectPerson");
                    String frontOperators = MapUtils.getString(item, "frontOperator");
                    Set<String> set = new HashSet<>();
                    if(StringUtils.isNotBlank(personss)){
                        List<Map<String, String>> list = JSON.parseObject(personss, List.class);
                        for (Map<String, String> map : list) {
                            set.add(map.get("id"));
                        }
                    }
                    if(StringUtils.isNotBlank(subjectPersons)){
                        List<Map<String, String>> list = JSON.parseObject(subjectPersons, List.class);
                        for (Map<String, String> map : list) {
                            set.add(map.get("id"));
                        }
                    }
                    if(StringUtils.isNotBlank(frontOperators)){
                        List<Map<String, String>> list = JSON.parseObject(frontOperators, List.class);
                        for (Map<String, String> map : list) {
                            set.add(map.get("id"));
                        }
                    }
                    for (String userId : set) {
                        if(onlineMapList.containsKey(userId)){
                            onlineMapList.get(userId).add("【"+projectName+"-"+postJDStr+"】");
                        }else{
                            List<String> list =   new ArrayList<>();
                            list.add("【"+projectName+"-"+postJDStr+"】");
                            onlineMapList.put(userId,list);
                        }
                    }
                }
            }

            for(String key: onlineMapList.keySet()){
                String value = "线上招聘需求：";
                List<String> values = onlineMapList.get(key);
                for(String item : values) {
                    value  += item + ",";
                }
                value = value.substring(0,value.length()-1);
                resultMap.put(key,value);
            }

            // 暂时还未提交周报，请尽快提交
            for(String key: offlineMapList.keySet()){
                String value = "线下招聘需求：";
                List<String> values = offlineMapList.get(key);
                for(String item : values) {
                    value  += item + ",";
                }
                value = value.substring(0,value.length()-1);
                if(resultMap.containsKey(key)){
                    resultMap.put(key,resultMap.get(key) + " " + value);
                }else{
                    resultMap.put(key,value);
                }
            }
        }

        return resultMap;
    }

    @Override
    public Map<String, String> getUnArchivedReportTips(String type) {
        Map<String, String> resultMap = new HashMap<>();
        Date startTime = getLastMonthFirstDay();
        Date endTime = getLastMonthLastDay();
        if("zx".equals(type)){
            Map<String, List<String>>  executeMapList = new HashMap<>();
            List<Map<String, Object>> executeReportMap = taskReportRepository.getUnArchivedExecuteReport(startTime,endTime);
            if(executeReportMap != null){
                for(Map item : executeReportMap) {
                    String projectName = item.get("projectNames").toString();
                    String activityName = item.get("activityName").toString();
                    String userId = item.get("operator").toString().split("\"")[3];
                    if (executeMapList.containsKey(userId)) {
                        executeMapList.get(userId).add("【"+projectName + "-" + activityName+"】");
                    } else {
                        List<String> list = new ArrayList<>();
                        list.add("【"+ projectName + "-" + activityName+"】");
                        executeMapList.put(userId, list);
                    }
                }
            }
            for(String key: executeMapList.keySet()){
                String value = "执行需求：";
                List<String> values = executeMapList.get(key);
                for(String item : values) {
                    value  += item + ",";
                }
                value = value.substring(0,value.length()-1);
                if(resultMap.containsKey(key)){
                    resultMap.put(key,resultMap.get(key) + " " + value);
                }else{
                    resultMap.put(key,value);
                }
            }
        }else if("zp".equals(type)){
            Map<String, List<String>>  offlineMapList = new HashMap<>();
            List<Map<String, Object>> offLineReportMap = taskReportRepository.getUnArchivedOffLineReport(startTime,endTime);
            if(offLineReportMap !=  null ){
                for(Map item : offLineReportMap){
                    String projectName = item.get("projectNames").toString();
                    String postJDStr = item.get("postJDStr").toString();
                    String userId = item.get("operator").toString().split("\"")[3];
                    if(offlineMapList.containsKey(userId)){
                        offlineMapList.get(userId).add("【"+projectName+"-"+postJDStr+"】");
                    }else{
                        List<String> list =   new ArrayList<>();
                        list.add("【"+projectName+"-"+postJDStr+"】");
                        offlineMapList.put(userId,list);
                    }
                }
            }
            // 暂时还未提交周报，请尽快提交
            for(String key: offlineMapList.keySet()){
                String value = "线下招聘需求：";
                List<String> values = offlineMapList.get(key);
                for(String item : values) {
                    value  += item + ",";
                }
                value = value.substring(0,value.length()-1);
                resultMap.put(key,value);
            }

        }
        return resultMap;
    }

    @Override
    public  List<Map<String, Object>> getNoContractProject(int startDays, int endDays) {
        List<Map<String, Object>>  resultMap =  new ArrayList<>();
        List<Map<String, Object>>  projectListMap  =  taskReportRepository.getNoContractProject(startDays, endDays);
        for(Map item : projectListMap){
            Map<String, Object> map = new HashMap();
            String id = item.get("id").toString();
            map.put("id",id);
            map.put("projectNames", item.get("projectNames").toString());
            map.put("subjectPerson", item.get("subjectPerson").toString().split("\"")[3]);
            map.put("days",item.get("days"));
            List<Map<String, Object>>  operatorMap = taskReportRepository.getOperators(id);
            List<String>  operators = new ArrayList<>();
            for(int i=0; i<operatorMap.size(); i++){
                Map<String, Object> tempMap = operatorMap.get(i);
                String operator = tempMap.get("operator").toString().split("\"")[3];
                operators.add(operator);
            }
            map.put("operator", operators);
            resultMap.add(map);
        }
        return resultMap;
    }

    @Override
    public Map<String, String> getDemandInfo(String demandId, String subSchemaCode) {
        if("XXZPXQZBGL".equals(subSchemaCode)){
            Map<String,String> map = taskReportRepository.getRecruitmentDemandInfo(demandId);
            Map<String, String> tmpMap = new HashMap<>();
            tmpMap.put("name", map.get("name").toString());
            tmpMap.put("operator",map.get("operator"));
            return tmpMap;
        }else if("ZXZBGL".equals(subSchemaCode)){
            Map<String,String> map =  taskReportRepository.getExecuteDemandInfo(demandId);

            Map<String, String> tmpMap = new HashMap<>();
            tmpMap.put("name", map.get("name").toString());
            tmpMap.put("operator",map.get("operator"));
            return tmpMap;
        }
        return  null;
    }

    @Override
    public String getProjectDirector(String userId, String projectDirectorRoleId) {
        return taskReportRepository.getProjectDirector(userId, projectDirectorRoleId);
    }

    @Override
    public List<Map<String, Object>> traceRecruitment(int days) {
        List<Map<String, Object>> resultMap = new ArrayList<>();
        List<Map<String, Object>> listMap = taskReportRepository.traceRecruitment(days);
        for(Map<String,Object> map : listMap){
            Map tempMap = new HashMap();
            tempMap.put("projectName", map.get("projectNameStr").toString());
            tempMap.put("postJD", map.get("postJDStr").toString());
            tempMap.put("operator", map.get("operator").toString().split("\"")[3]);
            tempMap.put("demandCreatedTime", map.get("demandCreatedTime"));
            tempMap.put("days", map.get("days"));
            resultMap.add(tempMap);

        }
        return resultMap;
    }

    @Override
    public void updateStoreInfo(String demandId,  String subjectName, List<Map<String, Object>> containsStores, String code) {
        if("zp".equals(code)) {
            for (Map<String, Object> storeMap : containsStores) {
                taskReportRepository.updateStoreInfoFromZP(demandId, subjectName, storeMap.get("storeCode"));
            }
        }else if("zx".equals(code)) {
            for (Map<String, Object> storeMap : containsStores) {
                taskReportRepository.updateStoreInfoFromZX(demandId, subjectName, storeMap.get("customerStoreNum"));
                taskReportRepository.updateStoreRCSArea(subjectName);
            }
        }else if("dj".equals(code)) {
            for (Map<String, Object> storeMap : containsStores) {
                taskReportRepository.updateStoreInfoFromDJ(demandId, subjectName, storeMap.get("storeCode"));
            }
        }
    }

    @Override
    public void createRecruitmentDetail(Map<String, Object> data) {
        taskReportRepository.createRecruitmentDetail(data.get("recruitmentId"),data.get("storeCode"),data.get("province"),data.get("areas"),
                data.get("storeName"),data.get("address"),data.get("area"),data.get("storeChannel"),data.get("storeContacts"),
                data.get("contactsPhone"),data.get("cityType"),data.get("workType"),data.get("isFixedWorkPlace"),data.get("isStore"), data.get("jobNature"),
                data.get("scale"),data.get("salaryCap"),data.get("contractType"),data.get("probationaryTime"),data.get("probationarySalary"),
                data.get("comment"),data.get("idCode"),data.get("demandFor"),data.get("modifier"),data.get("modifiedTime"), data.get("state"),data.get("city"),
                data.get("rcsArea"),data.get("id"));
    }

    @Override
    public void updateRecruitmentDetailStatus(List<String> idCodes, String state) {
        taskReportRepository.updateRecruitmentDetailStatus(idCodes,state);
    }

    @Override
    public void updateDetailStoreState(List<String> demandIds, String customerStoreNum, String state) {
        taskReportRepository.updateDetailStoreState(demandIds,customerStoreNum,state);
    }

    @Override
    public void updateDemandForById(String demandId, String recruitWay) {
        if("线上".equals(recruitWay)) {
            taskReportRepository.updateOnLineDemandForById(demandId);
        }else{
            taskReportRepository.updateOffLineDemandForById(demandId);
        }
    }

    @Override
    public void updateStoreRCSArea(String subjectName) {
        taskReportRepository.updateStoreRCSArea(subjectName);
    }

    @Override
    public void updateZPDetail(List<String> demandIds, String storeShortName, String rcsArea, String province, String cityName, String district, String detailArea, String area, String storeOutlet, String customDockingPerson, String customLinkType, String cityLevel, String customerStoreNum) {
        taskReportRepository.updateZPDetail(demandIds,storeShortName,rcsArea,province,cityName,district,detailArea,area,storeOutlet,customDockingPerson,customLinkType,cityLevel,customerStoreNum);
        taskReportRepository.updateOnLineReportDetail(demandIds,storeShortName,rcsArea,province,cityName,district,detailArea,area,customerStoreNum);
        taskReportRepository.updateOffLineReportDetail(demandIds,storeShortName,rcsArea,province,cityName,district,detailArea,area,customerStoreNum);
    }

    @Override
    public void updateDJDetail(List<String> demandIds, String storeShortName, String province, String cityName, String district, String detailArea, String area, String storeOutlet, String customDockingPerson, String customLinkType, String cityLevel, String customerStoreNum) {
        taskReportRepository.updateDJDetail(demandIds,storeShortName,province,cityName,district,detailArea,area,storeOutlet,customDockingPerson,customLinkType,cityLevel,customerStoreNum);
    }

    @Override
    public void clearFASQ(String id) {
        taskReportRepository.clearFASQ(id);
    }
}
